package com.io.controller;

import com.io.dao.UserDaoI;
import com.io.dto.UserReqDTO;
import com.io.dto.UserResDTO;
import com.io.entity.User;
import com.io.service.UserServiceI;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * The class/interface
 *
 * @author guodd
 * @version 1.0 use jdk 1.8
 */
@RestController
@Slf4j
public class UserController {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private UserDaoI userDaoI;

    @Autowired
    private UserServiceI userServiceI;

    // SQL注入攻击
    // http://localhost:8071/getUserByName?name=' or 1=1 or name= '
    @GetMapping(value = "/getUserByName")
    public List<User> getUserByName(String name) {
        String sql = "select * from user where name = '" + name + "'";

        // List<User> userList = jdbcTemplate.query(sql, new Object[]{}, new BeanPropertyRowMapper<>(User.class));
        List<User> userList = userDaoI.findByName(name);
        // List<User> users = jdbcTemplate.queryForList(sql, User.class);
        log.info("[{}]", userList);
        return userList;
    }

    // 注册用户
    @PostMapping(value = "/register")
    public UserResDTO register(@Validated UserReqDTO userReqDTO) {
        return userServiceI.register(userReqDTO);
    }

    // 注册用户
    @PostMapping(value = "/login")
    public UserResDTO login(@Validated UserReqDTO userReqDTO, HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.invalidate();
        }
        request.getSession(true).setAttribute("", "");
        return userServiceI.register(userReqDTO);
    }
}
